package com.fiap.gestaoPassagens.aeroporto;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.fiap.gestaoPassagens.dao.ConnectionFactory;


public class AeroportoDao {
	
	public List<AeroportoBean> listAeroporto(AeroportoBean aeroportoBean) throws SQLException {
		Connection con = ConnectionFactory.getConnection();
		PreparedStatement pstmt = null;
		StringBuffer sql = new StringBuffer();
		ResultSet rs = null;
		List<AeroportoBean> lista = new ArrayList<AeroportoBean>();

		try {
			sql.append(" SELECT * FROM  AEROPORTO ");
			sql.append(" WHERE 1=1 ");
			
			if (StringUtils.trimToNull(aeroportoBean.getSiglaAeroporto())!=null) {
				sql.append(" AND SIGLA_AEROPORTO = ? ");
			}

			sql.append(" ORDER BY 1,2 ");

			pstmt = con.prepareStatement(sql.toString());

			if (StringUtils.trimToNull(aeroportoBean.getSiglaAeroporto())!=null) {
				pstmt.setString(1, aeroportoBean.getSiglaAeroporto());
			}
			rs = pstmt.executeQuery();

			while (rs.next()) {
				lista.add(this.mountBean(rs));
			}

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		} finally {
			pstmt.close();
			con.close();
			rs.close();
		}
		return lista;
	}

	public AeroportoBean mountBean(ResultSet rs) throws SQLException {
		AeroportoBean a = new AeroportoBean();
		a.setSiglaAeroporto(rs.getString("SIGLA_AEROPORTO"));
		a.setUfAeroporto(rs.getString("UF_AEROPORTO"));
		a.setCidadeAeroporto(rs.getString("CIDADE_AEROPORTO"));

		return a;
	}
}
